<template>
  <div class="audit-log-container">
    <div class="filter-container">
      <el-form :inline="true" class="filter-form">
        <el-form-item :label="$t('auditLog.apiUrl') + ':'">
          <el-input
            v-model="listQuery.apiUrl"
            :placeholder="$t('auditLog.apiUrl')"
            style="width: 180px"
            class="filter-item"
            clearable
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item :label="$t('auditLog.clientIpAddress') + ':'">
          <el-input
            v-model="listQuery.clientIpAddress"
            :placeholder="$t('auditLog.clientIpAddress')"
            style="width: 150px"
            class="filter-item"
            clearable
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item :label="$t('auditLog.creatorId') + ':'">
          <el-select
            v-model="listQuery.creatorId"
            clearable
            filterable
            :placeholder="$t('auditLog.creatorId')"
            style="width: 120px"
            class="filter-item"
          >
            <el-option
              v-for="item in allUsers"
              :key="item.creatorId"
              :label="item.userName"
              :value="item.creatorId"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('auditLog.startTime') + ':'">
          <el-date-picker
            v-model="listQuery.timeRange"
            type="datetimerange"
            range-separator="~"
            :start-placeholder="$t('auditLog.startTime')"
            :end-placeholder="$t('auditLog.endTime')"
            style="width: 350px"
            class="filter-item"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item :label="$t('auditLog.auditLogType') + ':'">
          <el-checkbox-group
            v-model="listQuery.auditLogTypes"
            class="filter-item"
          >
            <el-checkbox :label="0">正常日志</el-checkbox>
            <el-checkbox :label="99">异常日志</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >
            {{ $t("table.search") }}
          </el-button>
          <el-button
            class="filter-item"
            style="margin-left: 10px"
            icon="el-icon-refresh-left"
            @click="handleReset"
          >
            {{ $t("table.reset") }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      class="audit-log-table"
    >
      <el-table-column
        :label="$t('table.id')"
        prop="id"
        align="center"
        width="80"
        fixed="left"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.date')" width="160px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.creationTime | parseTime("{y}-{m}-{d} {h}:{i}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('auditLog.apiUrl')"
        width="200px"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="{ row }">
          <span>{{ row.apiUrl }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('auditLog.method')"
        width="80px"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-tag :type="getMethodTagType(row.method)" size="mini">
            {{ row.method }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        :label="$t('auditLog.parameters')"
        width="120px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.parameters || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('auditLog.returnValue')"
        width="100px"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-tag
            :type="row.exceptionMessage ? 'danger' : 'success'"
            size="mini"
          >
            {{ row.exceptionMessage ? "异常" : "OK" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('auditLog.executionDuration') + '(ms)'"
        width="120px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span :class="getDurationClass(row.executionDuration)">
            {{ row.executionDuration }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('auditLog.clientIpAddress')"
        width="130px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.clientIpAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        :label="$t('auditLog.browserInfo')"
        width="150px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.browserInfo || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('auditLog.auditLogType')"
        class-name="status-col"
        width="100px"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-tag :type="row.auditLogType | auditLogTypeFilter" size="mini">
            {{ row.auditLogType | auditLogTypeTextFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('auditLog.creatorUserName')"
        width="110px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.creatorUserName || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        :label="$t('auditLog.exceptionMessage')"
        width="150px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span v-if="row.exceptionMessage" class="exception-text">
            {{ row.exceptionMessage }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="{ row, $index }">
          <el-button size="mini" type="primary" @click="handleDetail(row)">
            {{ $t("table.detail") }}
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            {{ $t("table.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="日志详情"
      :visible.sync="dialogFormVisible"
      width="60%"
      class="audit-log-detail-dialog"
    >
      <div class="dialog-content">
        <el-form
          ref="dataForm"
          :model="temp"
          label-position="left"
          label-width="140px"
          class="detail-form"
        >
          <el-form-item :label="$t('table.id') + ':'">
            <span>{{ temp.id }}</span>
          </el-form-item>
          <el-form-item :label="$t('table.date') + ':'">
            <span>{{
              temp.creationTime | parseTime("{y}-{m}-{d} {h}:{i}")
            }}</span>
          </el-form-item>
          <el-form-item :label="$t('auditLog.apiUrl') + ':'">
            <span>{{ temp.apiUrl }}</span>
          </el-form-item>
          <el-form-item :label="$t('auditLog.method') + ':'">
            <el-tag :type="getMethodTagType(temp.method)" size="mini">
              {{ temp.method }}
            </el-tag>
          </el-form-item>
          <el-form-item :label="$t('auditLog.parameters') + ':'">
            <div class="parameter-content">
              <pre v-if="temp.parameters">{{
                formatJsonString(temp.parameters)
              }}</pre>
              <span v-else>-</span>
            </div>
          </el-form-item>
          <el-form-item :label="$t('auditLog.returnValue') + ':'">
            <el-tag
              :type="temp.exceptionMessage ? 'danger' : 'success'"
              size="mini"
            >
              {{ temp.exceptionMessage ? "异常" : "OK" }}
            </el-tag>
          </el-form-item>
          <el-form-item :label="$t('auditLog.executionDuration') + '(ms)：'">
            <span :class="getDurationClass(temp.executionDuration)">
              {{ temp.executionDuration }}
            </span>
          </el-form-item>
          <el-form-item :label="$t('auditLog.clientIpAddress') + ':'">
            <span>{{ temp.clientIpAddress }}</span>
          </el-form-item>
          <el-form-item :label="$t('auditLog.browserInfo') + ':'">
            <div class="browser-info">
              {{ temp.browserInfo || "-" }}
            </div>
          </el-form-item>
          <el-form-item :label="$t('auditLog.auditLogType') + ':'">
            <el-tag :type="temp.auditLogType | auditLogTypeFilter" size="mini">
              {{ temp.auditLogType | auditLogTypeTextFilter }}
            </el-tag>
          </el-form-item>
          <el-form-item :label="$t('auditLog.creatorUserName') + ':'">
            <span>{{ temp.creatorUserName || "-" }}</span>
          </el-form-item>
          <el-form-item :label="$t('auditLog.exceptionMessage') + ':'">
            <div v-if="temp.exceptionMessage" class="exception-content">
              <pre class="exception-text">{{ temp.exceptionMessage }}</pre>
            </div>
            <span v-else>-</span>
          </el-form-item>
          <el-form-item :label="$t('auditLog.exception') + ':'">
            <div v-if="temp.exception" class="exception-content">
              <pre class="exception-text">{{ temp.exception }}</pre>
            </div>
            <div v-else>-</div>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible = false">
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { queryAllUsers } from '@/api/user'
import { queryAuditLogs, deleteAuditLog } from '@/api/auditlog'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'AuditLog',
  components: { Pagination },
  directives: { waves },
  filters: {
    auditLogTypeFilter(status) {
      const statusMap = {
        0: 'success',
        99: 'danger'
      }
      return statusMap[status] || 'info'
    },
    auditLogTypeTextFilter(status) {
      const statusMap = {
        0: '正常',
        99: '异常'
      }
      return statusMap[status] || '未知'
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 8,
        apiUrl: '',
        clientIpAddress: '',
        creatorId: null,
        timeRange: null,
        startTime: '',
        endTime: '',
        auditLogTypes: []
      },
      dialogFormVisible: false,
      temp: {},
      allUsers: []
    }
  },
  created() {
    this.getList()
    this.getAllUsers()
  },
  methods: {
    getList() {
      this.listLoading = true
      const timeRange = this.listQuery.timeRange
      if (timeRange) {
        this.listQuery.startTime = parseTime(timeRange[0])
        this.listQuery.endTime = parseTime(timeRange[1])
      } else {
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      }

      // 构建请求参数，确保数据类型正确
      const requestParams = this.processFilterParams(this.listQuery)

      console.log('Request Params:', requestParams) // 调试信息

      queryAuditLogs(requestParams)
        .then((response) => {
          console.log('API Response:', response) // 调试信息
          // 后端返回的字段可能是PascalCase，需要适配
          this.list = response.auditLogs || response.AuditLogs || []
          this.total = response.totalCount || response.TotalCount || 0
          this.listLoading = false
        })
        .catch((error) => {
          console.error('API Error:', error) // 错误调试信息
          this.listLoading = false
        })
    },
    getAllUsers() {
      queryAllUsers()
        .then((response) => {
          console.log('All Users Response:', response) // 调试信息
          this.allUsers = response || []
        })
        .catch((error) => {
          console.error('Get Users Error:', error)
          this.allUsers = []
        })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    handleReset() {
      // 重置所有筛选条件
      this.listQuery = {
        currentPage: 1,
        pageSize: 8,
        apiUrl: '',
        clientIpAddress: '',
        creatorId: null,
        timeRange: null,
        startTime: '',
        endTime: '',
        auditLogTypes: []
      }
      // 重置后重新加载数据
      this.getList()
      // 显示重置成功提示
      this.$message({
        type: 'success',
        message: '筛选条件已重置',
        duration: 1500
      })
    },
    handleDetail(row) {
      this.dialogFormVisible = true
      this.temp = Object.assign({}, row)
    },
    handleDelete(row, index) {
      this.$confirm('确认删除此日志?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteAuditLog(row.id).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.total--
          })
        })
        .catch(() => {
          this.$notify({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    getMethodTagType(method) {
      const methodTypes = {
        GET: 'success',
        POST: 'primary',
        PUT: 'warning',
        DELETE: 'danger',
        PATCH: 'info'
      }
      return methodTypes[method] || 'info'
    },
    getDurationClass(duration) {
      if (duration > 1000) {
        return 'duration-slow'
      } else if (duration > 500) {
        return 'duration-medium'
      }
      return 'duration-fast'
    },
    // 处理筛选参数，确保数据类型正确
    processFilterParams(params) {
      const processedParams = { ...params }

      // 确保auditLogTypes是数字数组
      if (
        processedParams.auditLogTypes &&
        processedParams.auditLogTypes.length > 0
      ) {
        processedParams.auditLogTypes = processedParams.auditLogTypes.map(
          (type) => {
            return typeof type === 'string' ? parseInt(type, 10) : type
          }
        )
      }

      // 确保creatorId是数字类型（如果有值）
      if (
        processedParams.creatorId !== null &&
        processedParams.creatorId !== undefined &&
        processedParams.creatorId !== ''
      ) {
        processedParams.creatorId =
          typeof processedParams.creatorId === 'string'
            ? parseInt(processedParams.creatorId, 10)
            : processedParams.creatorId
      }

      // 移除空值参数
      Object.keys(processedParams).forEach((key) => {
        if (
          processedParams[key] === '' ||
          processedParams[key] === null ||
          (Array.isArray(processedParams[key]) &&
            processedParams[key].length === 0)
        ) {
          delete processedParams[key]
        }
      })

      return processedParams
    },
    // 格式化JSON字符串，使其更易读
    formatJsonString(jsonStr) {
      if (!jsonStr) return ''
      try {
        // 尝试解析JSON并格式化
        const parsed = JSON.parse(jsonStr)
        return JSON.stringify(parsed, null, 2)
      } catch (e) {
        // 如果不是有效的JSON，直接返回原字符串
        return jsonStr
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.audit-log-container {
  .filter-container {
    background: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .filter-form {
      .el-form-item {
        margin-bottom: 15px;
        margin-right: 20px;

        .el-form-item__label {
          font-weight: 500;
          color: #606266;
        }

        // 按钮样式优化
        .el-button {
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
  }

  .audit-log-table {
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .exception-text {
      color: #f56c6c;
      font-size: 12px;
    }

    .duration-fast {
      color: #67c23a;
    }

    .duration-medium {
      color: #e6a23c;
    }

    .duration-slow {
      color: #f56c6c;
    }
  }

  .dialog-footer {
    text-align: center;
    padding-top: 20px;
  }

  .detail-form {
    .el-form-item {
      margin-bottom: 15px;

      .el-form-item__label {
        font-weight: 500;
        color: #606266;
      }

      span {
        color: #303133;
        word-break: break-all;
      }
    }
  }
}

// 对话框样式
::v-deep .audit-log-detail-dialog {
  .el-dialog {
    max-height: 90vh;
    display: flex;
    flex-direction: column;

    .el-dialog__body {
      flex: 1;
      overflow: hidden;
      padding: 10px 20px;
    }
  }

  .dialog-content {
    max-height: 60vh;
    overflow-y: auto;
    padding-right: 10px;

    // 自定义滚动条样式
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 3px;

      &:hover {
        background: #a8a8a8;
      }
    }
  }

  .detail-form {
    .el-form-item {
      margin-bottom: 20px;

      .el-form-item__label {
        font-weight: 500;
        color: #606266;
        line-height: 1.5;
      }

      .el-form-item__content {
        line-height: 1.5;
      }
    }

    .parameter-content,
    .exception-content {
      max-width: 100%;

      pre {
        background-color: #f5f5f5;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        padding: 12px;
        margin: 0;
        white-space: pre-wrap;
        word-wrap: break-word;
        font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
        font-size: 12px;
        line-height: 1.4;
        color: #333;
        max-height: 200px;
        overflow-y: auto;

        &::-webkit-scrollbar {
          width: 4px;
        }

        &::-webkit-scrollbar-track {
          background: #f1f1f1;
        }

        &::-webkit-scrollbar-thumb {
          background: #c1c1c1;
          border-radius: 2px;
        }
      }
    }

    .browser-info {
      word-break: break-all;
      line-height: 1.5;
    }

    .exception-text {
      color: #f56c6c;
    }
  }
}

// 全局样式调整
::v-deep .el-table {
  .el-table__header-wrapper {
    th {
      background-color: #fafafa;
      color: #606266;
      font-weight: 500;
    }
  }

  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

::v-deep .el-dialog {
  .el-dialog__header {
    background-color: #fafafa;
    padding: 20px 20px 10px;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  .el-dialog__body {
    padding: 20px;
  }
}

::v-deep .el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
